<template>
  <div id="app">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <div class="logo">
            <h2>甘特图编辑器</h2>
          </div>
          <div class="header-actions">
            <el-button type="text">设置</el-button>
            <el-button type="text">用户</el-button>
          </div>
        </div>
      </el-header>
      
      <el-main>
        <!-- 工具栏 -->
        <div class="toolbar">
          <h3>项目进度管理</h3>
          <div class="toolbar-actions">
            <el-button type="primary" @click="addTask">添加任务</el-button>
            <el-button @click="showExportDialog = true">导出数据</el-button>
            <el-button @click="showTimeRangeSelector = true">时间段选择</el-button>
            <el-select v-model="zoomLevel" style="width: 120px">
              <el-option label="25%" :value="0.25"></el-option>
              <el-option label="50%" :value="0.5"></el-option>
              <el-option label="100%" :value="1"></el-option>
              <el-option label="150%" :value="1.5"></el-option>
              <el-option label="200%" :value="2"></el-option>
            </el-select>
            <el-switch
              v-model="showToday"
              active-text="显示今天"
              inactive-text="隐藏今天">
            </el-switch>
            <el-switch
              v-model="showDependencyLines"
              active-text="显示依赖"
              inactive-text="隐藏依赖">
            </el-switch>
            <el-radio-group v-model="viewType" size="small">
              <el-radio-button label="day">日视图</el-radio-button>
              <el-radio-button label="week">周视图</el-radio-button>
            </el-radio-group>
          </div>
        </div>

        <!-- 统计面板 -->
        <div class="statistics-panel">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-number">{{ statistics.totalTasks }}</div>
                  <div class="stat-label">总任务数</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-number">{{ statistics.visibleTasks }}</div>
                  <div class="stat-label">显示任务数</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-number">{{ statistics.completedTasks }}</div>
                  <div class="stat-label">已完成</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div class="stat-content">
                  <div class="stat-number">{{ statistics.totalProgress }}%</div>
                  <div class="stat-label">平均进度</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        
        <!-- 甘特图 -->
        <GanttChart 
          :tasks="filteredTasks"
          :task-list-columns="taskListColumns"
          :all-columns="allColumns"
          :zoom-level="zoomLevel"
          :show-today="showToday"
          :show-dependency-lines="showDependencyLines"
          :time-range="[timelineStart, timelineEnd]"
          :view-type="viewType"
          @update-task="updateTask"
          @delete-task="deleteTask"
          @edit-task="editTask"
          @columns-change="handleColumnsChange"
        />
        
        <!-- 任务编辑对话框 -->
        <TaskEditDialog
          v-model="taskDialogVisible"
          :task="editingTask"
          :all-tasks="tasks"
          @save="saveTask"
        />

        <!-- 时间段选择器 -->
        <TimeRangeSelector
          v-model="showTimeRangeSelector"
          :current-range="[timelineStart, timelineEnd]"
          @range-change="handleTimeRangeChange"
        />

        <!-- 导出对话框 -->
        <ExportDialog
          v-model="showExportDialog"
          :tasks="tasks"
          :filtered-tasks="filteredTasks"
          :timeline="{ start: timelineStart?.format('YYYY-MM-DD') || '', end: timelineEnd?.format('YYYY-MM-DD') || '' }"
          :statistics="statistics"
          @export-success="handleExportSuccess"
        />


      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import GanttChart from './components/GanttChart.vue'
import TaskEditDialog from './components/TaskEditDialog.vue'
import TimeRangeSelector from './components/TimeRangeSelector.vue'
import ExportDialog from './components/ExportDialog.vue'

import DateRenderer from './components/column-renderers/DateRenderer.vue'
import PriorityRenderer from './components/column-renderers/PriorityRenderer.vue'
import StatusRenderer from './components/column-renderers/StatusRenderer.vue'
import ProgressRenderer from './components/column-renderers/ProgressRenderer.vue'
import dayjs from 'dayjs'
import { v4 as uuidv4 } from 'uuid'

export default {
  name: 'App',
  components: {
    GanttChart,
    TaskEditDialog,
    TimeRangeSelector,
    ExportDialog,

    DateRenderer,
    PriorityRenderer,
    StatusRenderer,
    ProgressRenderer
  },
  setup() {
    const zoomLevel = ref(1)
    const showToday = ref(true)
    const showDependencyLines = ref(true)
    const taskDialogVisible = ref(false)
    const editingTask = ref(null)
    const showTimeRangeSelector = ref(false)
    const showExportDialog = ref(false)

    const viewType = ref('day') // 'day' | 'week'
    
    // 时间范围
    const timelineStart = ref(dayjs('2024-01-01'))
    const timelineEnd = ref(dayjs('2024-04-15'))
    
    // 所有可用列定义
    const allColumns = ref([
      {
        key: 'name',
        label: '任务名称',
        width: 200,
        sortable: true
      },
      {
        key: 'assignee',
        label: '责任人',
        width: 80,
        sortable: true
      },
      {
        key: 'startDate',
        label: '开始时间',
        width: 80,
        sortable: true,
        renderer: DateRenderer
      },
      {
        key: 'endDate',
        label: '结束时间',
        width: 80,
        sortable: true,
        renderer: DateRenderer
      },
      {
        key: 'progress',
        label: '进度',
        width: 100,
        sortable: true,
        renderer: ProgressRenderer
      },
      {
        key: 'priority',
        label: '优先级',
        width: 70,
        sortable: true,
        renderer: PriorityRenderer
      },
      {
        key: 'status',
        label: '状态',
        width: 80,
        sortable: true,
        renderer: StatusRenderer
      },
      {
        key: 'level',
        label: '层级',
        width: 60,
        sortable: true
      },
      {
        key: 'parentId',
        label: '父任务',
        width: 80,
        sortable: true
      },
      {
        key: 'dependencies',
        label: '依赖',
        width: 100,
        sortable: false
      }
    ])
    
    // 任务列表列配置
    const taskListColumns = ref([
      {
        key: 'name',
        label: '任务名称',
        width: 200,
        sortable: true
      },
      {
        key: 'assignee',
        label: '责任人',
        width: 80,
        sortable: true
      },
      {
        key: 'startDate',
        label: '开始时间',
        width: 80,
        sortable: true,
        renderer: DateRenderer
      },
      {
        key: 'endDate',
        label: '结束时间',
        width: 80,
        sortable: true,
        renderer: DateRenderer
      },
      {
        key: 'progress',
        label: '进度',
        width: 100,
        sortable: true,
        renderer: ProgressRenderer
      },
      {
        key: 'priority',
        label: '优先级',
        width: 70,
        sortable: true,
        renderer: PriorityRenderer
      },
      {
        key: 'status',
        label: '状态',
        width: 80,
        sortable: true,
        renderer: StatusRenderer
      }
    ])
    
    // 调试：检查初始列配置的renderer
    console.log('App - 初始taskListColumns:', taskListColumns.value)
    taskListColumns.value.forEach(col => {
      if (col.renderer) {
        console.log(`App - 初始列 ${col.key} 的renderer:`, col.renderer)
        console.log(`App - 初始列 ${col.key} 的renderer类型:`, typeof col.renderer)
        console.log(`App - 初始列 ${col.key} 的renderer名称:`, col.renderer.name)
      }
    })
    
    const tasks = reactive([
      {
        id: '1',
        name: '项目启动',
        startDate: dayjs('2024-01-01'),
        endDate: dayjs('2024-01-15'),
        progress: 100,
        color: '#67C23A',
        assignee: '张三',
        priority: 'high',
        status: 'completed',
        parentId: null,
        dependencies: []
      },
      {
        id: '2',
        name: '需求分析',
        startDate: dayjs('2024-01-10'),
        endDate: dayjs('2024-01-25'),
        progress: 80,
        color: '#409EFF',
        assignee: '李四',
        priority: 'high',
        status: 'in-progress',
        parentId: null,
        dependencies: ['1']
      },
      {
        id: '3',
        name: '系统设计',
        startDate: dayjs('2024-01-20'),
        endDate: dayjs('2024-02-10'),
        progress: 60,
        color: '#E6A23C',
        assignee: '王五',
        priority: 'medium',
        status: 'in-progress',
        parentId: null,
        dependencies: ['2']
      },
      {
        id: '4',
        name: '详细设计',
        startDate: dayjs('2024-01-25'),
        endDate: dayjs('2024-02-15'),
        progress: 40,
        color: '#F56C6C',
        assignee: '赵六',
        priority: 'medium',
        status: 'in-progress',
        parentId: '3',
        dependencies: ['3']
      },
      {
        id: '5',
        name: '编码实现',
        startDate: dayjs('2024-02-05'),
        endDate: dayjs('2024-03-20'),
        progress: 30,
        color: '#909399',
        assignee: '钱七',
        priority: 'low',
        status: 'pending',
        parentId: '3',
        dependencies: ['4']
      },
      {
        id: '6',
        name: '数据库设计',
        startDate: dayjs('2024-01-30'),
        endDate: dayjs('2024-02-20'),
        progress: 70,
        color: '#9C27B0',
        assignee: '孙八',
        priority: 'high',
        status: 'in-progress',
        parentId: '3',
        dependencies: ['3']
      },
      {
        id: '7',
        name: '前端开发',
        startDate: dayjs('2024-02-10'),
        endDate: dayjs('2024-03-25'),
        progress: 25,
        color: '#FF9800',
        assignee: '周九',
        priority: 'medium',
        status: 'in-progress',
        parentId: '5',
        dependencies: ['5']
      },
      {
        id: '8',
        name: '后端开发',
        startDate: dayjs('2024-02-12'),
        endDate: dayjs('2024-03-28'),
        progress: 20,
        color: '#795548',
        assignee: '吴十',
        priority: 'medium',
        status: 'in-progress',
        parentId: '5',
        dependencies: ['5']
      },
      {
        id: '9',
        name: 'API接口开发',
        startDate: dayjs('2024-02-15'),
        endDate: dayjs('2024-03-15'),
        progress: 45,
        color: '#607D8B',
        assignee: '郑十一',
        priority: 'medium',
        status: 'in-progress',
        parentId: '8',
        dependencies: ['8']
      },
      {
        id: '9-1',
        name: '用户认证API',
        startDate: dayjs('2024-02-18'),
        endDate: dayjs('2024-02-25'),
        progress: 80,
        color: '#607D8B',
        assignee: '郑十一',
        priority: 'medium',
        status: 'in-progress',
        parentId: '9',
        dependencies: ['9']
      },
      {
        id: '9-2',
        name: '数据查询API',
        startDate: dayjs('2024-02-20'),
        endDate: dayjs('2024-03-05'),
        progress: 60,
        color: '#607D8B',
        assignee: '郑十一',
        priority: 'medium',
        status: 'in-progress',
        parentId: '9',
        dependencies: ['9']
      },
      {
        id: '10',
        name: '用户界面设计',
        startDate: dayjs('2024-02-01'),
        endDate: dayjs('2024-02-20'),
        progress: 90,
        color: '#E91E63',
        assignee: '王十二',
        priority: 'medium',
        status: 'in-progress',
        parentId: '7',
        dependencies: ['7']
      },
      {
        id: '11',
        name: '单元测试',
        startDate: dayjs('2024-02-25'),
        endDate: dayjs('2024-03-30'),
        progress: 15,
        color: '#4CAF50',
        assignee: '李十三',
        priority: 'low',
        status: 'pending',
        parentId: '5',
        dependencies: ['7', '8']
      },
      {
        id: '12',
        name: '集成测试',
        startDate: dayjs('2024-03-01'),
        endDate: dayjs('2024-03-25'),
        progress: 10,
        color: '#8BC34A',
        assignee: '张十四',
        priority: 'medium',
        status: 'pending',
        parentId: '11',
        dependencies: ['11']
      },
      {
        id: '13',
        name: '性能测试',
        startDate: dayjs('2024-03-05'),
        endDate: dayjs('2024-03-20'),
        progress: 5,
        color: '#FFC107',
        assignee: '陈十五',
        priority: 'low',
        status: 'pending',
        parentId: '11',
        dependencies: ['11']
      },
      {
        id: '14',
        name: '文档编写',
        startDate: dayjs('2024-02-20'),
        endDate: dayjs('2024-03-25'),
        progress: 35,
        color: '#00BCD4',
        assignee: '刘十六',
        priority: 'low',
        status: 'in-progress',
        parentId: null,
        dependencies: ['3']
      },
      {
        id: '15',
        name: '用户手册',
        startDate: dayjs('2024-03-01'),
        endDate: dayjs('2024-03-20'),
        progress: 20,
        color: '#9E9E9E',
        assignee: '黄十七',
        priority: 'low',
        status: 'in-progress',
        parentId: '14',
        dependencies: ['14']
      },
      {
        id: '16',
        name: '技术文档',
        startDate: dayjs('2024-02-25'),
        endDate: dayjs('2024-03-15'),
        progress: 50,
        color: '#3F51B5',
        assignee: '马十八',
        priority: 'medium',
        status: 'in-progress',
        parentId: '14',
        dependencies: ['14']
      },
      {
        id: '17',
        name: '部署准备',
        startDate: dayjs('2024-03-15'),
        endDate: dayjs('2024-03-25'),
        progress: 0,
        color: '#FF5722',
        assignee: '赵十九',
        priority: 'high',
        status: 'pending',
        parentId: null,
        dependencies: ['12', '13']
      },
      {
        id: '18',
        name: '生产环境部署',
        startDate: dayjs('2024-03-20'),
        endDate: dayjs('2024-03-30'),
        progress: 0,
        color: '#673AB7',
        assignee: '钱二十',
        priority: 'high',
        status: 'pending',
        parentId: '17',
        dependencies: ['17']
      },
      {
        id: '19',
        name: '用户培训',
        startDate: dayjs('2024-03-25'),
        endDate: dayjs('2024-04-05'),
        progress: 0,
        color: '#2196F3',
        assignee: '孙二一',
        priority: 'medium',
        status: 'pending',
        parentId: null,
        dependencies: ['18']
      },
      {
        id: '20',
        name: '项目验收',
        startDate: dayjs('2024-04-01'),
        endDate: dayjs('2024-04-10'),
        progress: 0,
        color: '#4CAF50',
        assignee: '李二二',
        priority: 'high',
        status: 'pending',
        parentId: null,
        dependencies: ['19']
      }
    ])

    // 过滤任务（基于时间范围）
    const filteredTasks = computed(() => {
      console.log('App - 总任务数:', tasks.length)
      
      // 安全检查timelineStart和timelineEnd
      if (!timelineStart.value || !timelineEnd.value) {
        console.log('App - 时间范围未初始化，返回所有任务')
        return tasks
      }
      
      console.log('App - 时间范围:', {
        start: timelineStart.value.format('YYYY-MM-DD'),
        end: timelineEnd.value.format('YYYY-MM-DD')
      })
      
      const filtered = tasks.filter(task => {
        const taskStart = task.startDate
        const taskEnd = task.endDate
        
        // 安全检查任务日期
        if (!taskStart || !taskEnd) {
          console.warn(`任务 ${task.name} 的日期无效`)
          return false
        }
        
        const isInRange = (
          (taskStart.isAfter(timelineStart.value) || taskStart.isSame(timelineStart.value, 'day')) &&
          (taskEnd.isBefore(timelineEnd.value) || taskEnd.isSame(timelineEnd.value, 'day'))
        )
        
        // 调试信息
        console.log(`任务 ${task.name}:`, {
          taskStart: taskStart.format('YYYY-MM-DD'),
          taskEnd: taskEnd.format('YYYY-MM-DD'),
          timelineStart: timelineStart.value.format('YYYY-MM-DD'),
          timelineEnd: timelineEnd.value.format('YYYY-MM-DD'),
          isInRange
        })
        
        return isInRange
      })
      
      console.log('过滤后的任务数量:', filtered.length)
      return filtered
    })

    // 统计信息
    const statistics = computed(() => {
      const totalTasks = tasks.length
      const visibleTasks = filteredTasks.value.length
      const completedTasks = filteredTasks.value.filter(t => t.status === 'completed').length
      const inProgressTasks = filteredTasks.value.filter(t => t.status === 'in-progress').length
      const pendingTasks = filteredTasks.value.filter(t => t.status === 'pending').length
      
      const totalProgress = filteredTasks.value.length > 0 
        ? filteredTasks.value.reduce((sum, task) => sum + task.progress, 0) / filteredTasks.value.length 
        : 0
      
      return {
        totalTasks,
        visibleTasks,
        completedTasks,
        inProgressTasks,
        pendingTasks,
        totalProgress: Math.round(totalProgress)
      }
    })
    
    const addTask = () => {
      editingTask.value = null // 设置为null表示新建任务
      taskDialogVisible.value = true
    }
    
    const editTask = (task) => {
      editingTask.value = { ...task }
      taskDialogVisible.value = true
    }
    
    const saveTask = (taskData) => {
      // 验证前置任务依赖关系
      if (taskData.dependencies && taskData.dependencies.length > 0) {
        const validationResult = validateDependencies(taskData.dependencies, editingTask.value?.id)
        if (!validationResult.valid) {
          ElMessage.error(validationResult.message)
          return
        }
      }
      
      // 确保startDate和endDate是dayjs对象
      const processedTaskData = {
        ...taskData,
        startDate: dayjs(taskData.startDate),
        endDate: dayjs(taskData.endDate)
      }
      
      if (editingTask.value && editingTask.value.id) {
        // 编辑现有任务
        const index = tasks.findIndex(t => t.id === editingTask.value.id)
        if (index !== -1) {
          // 更新任务数据
          tasks[index] = { ...tasks[index], ...processedTaskData }
          
          // 如果修改了parentId，需要更新所有子任务的level
          if (processedTaskData.parentId !== tasks[index].parentId) {
            updateChildrenLevels(tasks[index].id, processedTaskData.level)
          }
        }
      } else {
        // 添加新任务
        const newTask = {
          ...processedTaskData,
          id: uuidv4() // 确保新任务有唯一ID
        }
        tasks.push(newTask)
      }
      taskDialogVisible.value = false
      editingTask.value = null
    }
    
    // 验证前置任务依赖关系
    const validateDependencies = (dependencies, currentTaskId) => {
      if (!dependencies || dependencies.length === 0) {
        return { valid: true }
      }
      
      // 检查依赖任务是否存在
      for (const depId of dependencies) {
        const depTask = tasks.find(t => t.id === depId)
        if (!depTask) {
          return { 
            valid: false, 
            message: `前置任务不存在: ${depId}` 
          }
        }
      }
      
      // 检查循环依赖
      if (currentTaskId) {
        const hasCircularDependency = checkCircularDependency(currentTaskId, dependencies)
        if (hasCircularDependency) {
          return { 
            valid: false, 
            message: '检测到循环依赖，请检查前置任务设置' 
          }
        }
      }
      
      return { valid: true }
    }
    
    // 检查循环依赖
    const checkCircularDependency = (taskId, dependencies) => {
      const visited = new Set()
      const recursionStack = new Set()
      
      const dfs = (currentId) => {
        if (recursionStack.has(currentId)) {
          return true // 发现循环
        }
        if (visited.has(currentId)) {
          return false
        }
        
        visited.add(currentId)
        recursionStack.add(currentId)
        
        const task = tasks.find(t => t.id === currentId)
        if (task && task.dependencies) {
          for (const depId of task.dependencies) {
            if (dfs(depId)) {
              return true
            }
          }
        }
        
        recursionStack.delete(currentId)
        return false
      }
      
      // 检查新添加的依赖是否会导致循环
      for (const depId of dependencies) {
        if (dfs(depId)) {
          return true
        }
      }
      
      return false
    }
    
    // 递归更新子任务的层级
    const updateChildrenLevels = (parentId, parentLevel) => {
      const children = tasks.filter(t => t.parentId === parentId)
      children.forEach(child => {
        child.level = parentLevel + 1
        updateChildrenLevels(child.id, child.level)
      })
    }
    
    const updateTask = (taskId, updates) => {
      const index = tasks.findIndex(t => t.id === taskId)
      if (index !== -1) {
        let processedUpdates = { ...updates }
        
        // 移除 viewType，因为它不是任务属性
        delete processedUpdates.viewType
        
        tasks[index] = { ...tasks[index], ...processedUpdates }
      }
    }
    
    const deleteTask = (taskId) => {
      const index = tasks.findIndex(t => t.id === taskId)
      if (index !== -1) {
        tasks.splice(index, 1)
      }
    }

    // 时间段选择处理
    const handleTimeRangeChange = (range) => {
      timelineStart.value = range[0]
      timelineEnd.value = range[1]
    }

    // 导出成功处理
    const handleExportSuccess = (result) => {
      console.log('导出成功:', result)
    }
    
    // 处理列配置变化（来自TaskList组件）
    const handleColumnsChange = (newColumns) => {
      console.log('App - 收到列配置变化:', newColumns)
      console.log('App - 更新前的列配置:', taskListColumns.value)
      
      // 检查renderer属性
      newColumns.forEach(col => {
        console.log(`App - 列 ${col.key} 的renderer:`, col.renderer)
      })
      
      taskListColumns.value = newColumns
      console.log('App - 更新后的列配置:', taskListColumns.value)
      ElMessage.success('列配置已更新')
    }
    
    return {
      zoomLevel,
      showToday,
      showDependencyLines,
      taskDialogVisible,
      editingTask,
      showTimeRangeSelector,
      showExportDialog,
      viewType,
      timelineStart,
      timelineEnd,
      tasks,
      filteredTasks,
      statistics,
      taskListColumns,
      allColumns,
      addTask,
      editTask,
      saveTask,
      updateTask,
      deleteTask,
      updateChildrenLevels,
      validateDependencies,
      checkCircularDependency,
      handleTimeRangeChange,
      handleExportSuccess,
      handleColumnsChange
    }
  }
}
</script>

<style>
#app {
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
  height: 100vh;
}

.header {
  background: #409EFF;
  color: white;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.logo h2 {
  margin: 0;
  font-size: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.toolbar h3 {
  margin: 0;
  color: #303133;
}

.toolbar-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.statistics-panel {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-content {
  padding: 10px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.el-main {
  padding: 20px;
  background: #f0f2f5;
}
</style>